<template>
  <el-select v-bind="props.selectProps" v-model="modelValue" @change="change">
    <el-option
      v-for="(item, index) in optionDataList"
      :key="index"
      :label="item[props.selectLabel]"
      :value="props.selectValue ? item[props.selectValue] : item"
    />
  </el-select>
</template>

<script lang="ts" setup>
import { ref, computed, WritableComputedRef, onMounted } from "vue";
import request from "~/api/interception";
import { _canArray } from "./../utils/utils";

interface IOptionParams {
  label?: string;
  value?: string;
}

interface IXSelectProps {
  modelValue: any;
  selectProps?: object;
  selectLabel?: string;
  selectValue?: string;
  remoteParams?: object;
  remoteUrl?: string;
  formateResFun?: (res: any) => IOptionParams[];
  requestFun?: Array<any> | (() => IOptionParams[]);
}

/**
 * @name: 2712638312@qq.com
 * @desc: emit 回调事件定义
 */
const emit = defineEmits<{
  (e: "update:modelValue", data: string): void;
  (e: "change", data: any): void;
}>();

/**
 * @name: 2712638312@qq.com
 * @desc: 默认赋值 props
 */
const props = withDefaults(defineProps<IXSelectProps>(), {
  modelValue: "",
  selectProps: () => {
    return {};
  },
  remoteParams: () => {
    return {};
  },
  selectLabel: "label",
  selectValue: "value",
  remoteUrl: "",
  formateResFun: () => {
    return [];
  },
  requestFun: () => {
    return [];
  },
});

// option 配置列表
const optionDataList = ref<IOptionParams[]>([]);
const modelValue: WritableComputedRef<string> = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  },
});

/**
 * @name: 2712638312@qq.com
 * @desc: change 事件
 */
const change = (res) => {
  emit("change", res);
};

/**
 * @name: 2712638312@qq.com
 * @desc: 格式化返回数据
 */
const formateRes = (res) => {
  if (props.formateResFun) {
    return props.formateResFun(res);
  } else {
    return res;
  }
};

/**
 * @name: 2712638312@qq.com
 * @desc: 获取option 列表
 */
const getOptionList = async () => {
  const { requestFun, remoteUrl, remoteParams } = props;
  if (_canArray(requestFun)) {
    optionDataList.value = (await requestFun) as Array<any>;
  } else if (typeof requestFun === "function") {
    optionDataList.value = await requestFun();
  } else if (remoteUrl) {
    request.post(remoteUrl, remoteParams).then((res) => {
      optionDataList.value = formateRes(res);
    });
  }
  console.log(optionDataList.value, "optionDataList");
};

onMounted(() => {
  getOptionList();
});

defineExpose({ getOptionList });
</script>

<style lang="scss" scoped></style>
